﻿using System;
using System.Linq.Expressions;

namespace TSharp.Core.Pattern
{
    /// <summary>
    /// 单例创建工厂
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <author>
    /// tangjingbo
    /// </author> 
    public class SingletonHelper<T> where T : class
    {
        private static readonly int[] sync = new int[0];
        private static T singleton;

        /// <summary>
        /// 获取单例，如果不存在则创建
        /// </summary>
        /// <param name="createrExpression">The creater expression.</param>
        /// <returns></returns>
        public static T GetOrAdd(Func<T> createrExpression)
        {
            if (singleton != null)
                return singleton;
            lock (sync)
            {
                if (singleton == null)
                {
                    singleton = createrExpression();
                }
                return singleton;
            }
        }


        /// <summary>
        /// 返回旧对象
        /// </summary>
        /// <param name="createrExpression">The creater.</param>
        /// <returns></returns>
        public static T Reset(Func<T> createrExpression)
        {
            T temp = singleton;
            singleton = null;
            singleton = GetOrAdd(createrExpression);
            return temp;
        }
    }
}